"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { fetchCommonQuestions, type FaqItem } from "@/lib/faq-api";
import { InlineLoading } from "@/components/ui/loading-state";
import { cn } from "@/lib/utils";

function Chevron({ className }: { className?: string }) {
  return (
    <svg
      aria-hidden
      viewBox="0 0 24 24"
      className={cn("h-5 w-5 shrink-0 text-slate-400", className)}
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

export function FaqClient() {
  const t = useTranslations("faq");
  const [items, setItems] = useState<FaqItem[] | null>(null);
  const [failed, setFailed] = useState(false);
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  useEffect(() => {
    let cancelled = false;
    void fetchCommonQuestions().then(({ items: next, failed: err }) => {
      if (cancelled) return;
      setItems(next);
      setFailed(err);
    });
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <div className="mx-auto max-w-3xl">
      <div className="text-center sm:text-left">
        <h1 className="font-serif text-3xl font-semibold tracking-tight text-[var(--navy)] md:text-4xl">
          {t("title")}
        </h1>
        <p className="mt-2 text-sm text-[var(--muted)]">{t("subtitle")}</p>
      </div>

      {items === null ? (
        <div className="mt-10 flex justify-center sm:justify-start">
          <InlineLoading text={t("loading")} />
        </div>
      ) : failed ? (
        <p className="mt-10 rounded-xl border border-rose-200/80 bg-rose-50/80 px-4 py-3 text-sm text-rose-800">
          {t("loadError")}
        </p>
      ) : items.length === 0 ? (
        <p className="mt-10 rounded-xl border border-dashed border-[var(--border)] bg-white/60 px-4 py-8 text-center text-sm text-[var(--muted)]">
          {t("empty")}
        </p>
      ) : (
        <div className="mt-10 overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] shadow-card">
          <ul className="divide-y divide-[var(--border)]" role="list">
            {items.map((item, index) => {
              const open = openIndex === index;
              return (
                <li key={`${item.id}-${index}`}>
                  <button
                    type="button"
                    id={`faq-trigger-${index}`}
                    aria-expanded={open}
                    aria-controls={`faq-panel-${index}`}
                    className={cn(
                      "flex w-full items-start justify-between gap-4 px-5 py-4 text-left transition-colors sm:px-6 sm:py-5",
                      open
                        ? "bg-gradient-to-r from-blue-50/90 to-slate-50/40"
                        : "hover:bg-slate-50/80",
                    )}
                    onClick={() => setOpenIndex(open ? null : index)}
                  >
                    <span
                      className={cn(
                        "min-w-0 flex-1 text-[15px] font-semibold leading-snug sm:text-base",
                        open ? "text-[var(--navy)]" : "text-slate-800",
                      )}
                    >
                      {item.question}
                    </span>
                    <Chevron
                      className={cn(
                        "mt-0.5 transition-transform duration-300 ease-out",
                        open && "rotate-180 text-blue-600",
                      )}
                    />
                  </button>
                  <div
                    id={`faq-panel-${index}`}
                    role="region"
                    aria-labelledby={`faq-trigger-${index}`}
                    className={cn(
                      "grid transition-[grid-template-rows] duration-300 ease-out",
                      open ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
                    )}
                  >
                    <div className="min-h-0 overflow-hidden">
                      <div className="border-t border-[var(--border)] bg-[var(--surface-muted)]/50 px-5 py-4 sm:px-6 sm:py-5">
                        <p className="whitespace-pre-wrap text-[15px] leading-relaxed text-slate-600">
                          {item.answer}
                        </p>
                      </div>
                    </div>
                  </div>
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </div>
  );
}
